﻿/*************************************************************************************
 * 工    具：  HK_SimpleVideoCtrl
 * 
 * 描    述：  简易视频播放工具
 * 
 * 版    本：  V1.3
 * 作    者：  谭潇杰、京产肠饭
 * 
 * 创    建：  2021/09/15  V1.0
 *
 * 更    新：  2025/03/29  V1.1
 *             1.功能优化：增加播放器状态管理，防止视频切换时的状态冲突
 *             2.代码优化：对 videoPlayer 的prepareCompleted事件进行了优化，避免重复注册    
 *             3.功能优化：增强平台兼容性
 *             4.性能优化：增强RenderTexture资源管理，防止纹理资源泄露
 *
 *             2025/03/30  V1.2
 *             1.功能优化：合并视频暂停功能，减少无用脚本
 *             2.代码优化：整合协程方法，作为局部函数增强代码内聚性
 *
 *             2025/04/08  V1.3
 *             1.功能新增：增加 SetPlaybackSpeed(float speed) 方法，设置播放速度
 * 
 * 链    接：  https://gitee.com/JingChanChangFan/hk_-unity-tools
*************************************************************************************/

using System;
using System.Collections;
using QFramework;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.Video;

namespace HKTools
{
    public class HK_SimpleVideoCtrl : MonoBehaviour, IPointerDownHandler
    {
        [Header("VideoPlayer组件"), SerializeField]
        VideoPlayer videoPlayer;

        // 视频暂停提示
        Image pause_Img;
        bool isPaused;

        void OnEnable()
        {
            pause_Img = transform.Find("Pause_Img").GetComponent<Image>();
            pause_Img.Hide();

            if (videoPlayer.targetTexture != null && videoPlayer.targetTexture.IsCreated())
            {
                videoPlayer.targetTexture.Release();
            }
        }

        void OnDisable()
        {
            StopVideo();
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            PauseVideo();
        }

        void PlayVideo(Action playVideoAction)
        {
            IEnumerator IE_DelayedPlay()
            {
                yield return null;
                playVideoAction?.Invoke();
            }

            if (videoPlayer.isPlaying || videoPlayer.isPrepared)
            {
                StopVideo();
                StartCoroutine(IE_DelayedPlay());
                return;
            }
            playVideoAction?.Invoke();
        }

        /// <summary>
        /// 通过 VideoClip 播放视频
        /// </summary>
        public void PlayClipVideo(VideoClip videoClip, bool isLooping = false)
        {
            PlayVideo(() =>
            {
                if (videoPlayer.source != VideoSource.VideoClip)
                    videoPlayer.source = VideoSource.VideoClip;

                if (videoClip != null)
                    videoPlayer.clip = videoClip;

                SetupVideoPlayer(isLooping);
            });
        }

        /// <summary>
        /// 通过 URL 播放视频
        /// </summary>
        public void PlayURLVideo(string url, bool isLooping = false)
        {
            PlayVideo(() =>
            {
                if (videoPlayer.source != VideoSource.Url)
                    videoPlayer.source = VideoSource.Url;

                if (!string.IsNullOrEmpty(url))
                    videoPlayer.url = url;

                SetupVideoPlayer(isLooping);
            });
        }

        /// <summary>
        /// 通过 StreamingAssets 播放视频
        /// </summary>
        public void PlayStreamingAssetsVideo(string videoName, bool isLooping = false)
        {
            PlayVideo(() =>
            {
                if (videoPlayer.source != VideoSource.Url)
                    videoPlayer.source = VideoSource.Url;

#if UNITY_ANDROID && !UNITY_EDITOR
                var filePath = $"file://{System.IO.Path.Combine(Application.streamingAssetsPath, videoName)}";
#else
                var filePath = System.IO.Path.Combine(Application.streamingAssetsPath, videoName);
#endif

                videoPlayer.url = filePath;

                SetupVideoPlayer(isLooping);
            });
        }

        /// <summary>
        /// 设置播放速度
        /// </summary>
        /// <param name="speed"> 播放速度 </param>
        public void SetPlaybackSpeed(float speed)
        {
            videoPlayer.playbackSpeed = speed;
        }

        void SetupVideoPlayer(bool isLooping = false)
        {
            SetPlaybackSpeed(1);

            videoPlayer.isLooping = isLooping;
            pause_Img.Hide();
            videoPlayer.SetDirectAudioMute(0, false);

            videoPlayer.prepareCompleted -= OnPrepareCompleted;
            videoPlayer.prepareCompleted += OnPrepareCompleted;

            videoPlayer.Prepare();
            isPaused = false;
        }

        void OnPrepareCompleted(VideoPlayer source)
        {
            try
            {
                videoPlayer.Play();
            }
            finally
            {
                videoPlayer.prepareCompleted -= OnPrepareCompleted; // 重要：解除事件绑定
            }
        }

        /// <summary>
        /// 暂停视频
        /// </summary>
        public void PauseVideo()
        {
            if (videoPlayer.clip == null && videoPlayer.url == "")
                return;

            isPaused = !isPaused;
            pause_Img.gameObject.SetActive(isPaused);

            if (!isPaused)
                videoPlayer.Play();
            else
                videoPlayer.Pause();
        }

        /// <summary>
        /// 停止播放
        /// </summary>
        public void StopVideo()
        {
            videoPlayer.Stop();

            // 添加目标纹理存在检查
            if (videoPlayer.targetTexture != null)
            {
                videoPlayer.targetTexture.Release(); // 释放 GPU 资源
                // 添加纹理重置操作
                RenderTexture.active = null;         // 清除当前激活的 RenderTexture
            }

            videoPlayer.clip = null;
            videoPlayer.url = string.Empty;
            isPaused = false;
            pause_Img.Hide();
        }
    }
}